<template>
  <div>
    <div ref="divRef" style="height: 500px" />
  </div>
</template>

<script>
import axios from "axios"
import { AiEditor } from "aieditor";
import "aieditor/dist/style.css"
import { getToken } from "@/utils/auth"

export default {
  name: "Editor",
  props: {
    /* 编辑器的内容 */
    value: {
      type: String,
      default: "",
    },
    /* 高度 */
    height: {
      type: Number,
      default: null,
    },
    /* 最小高度 */
    minHeight: {
      type: Number,
      default: null,
    },
    /* 只读 */
    readOnly: {
      type: Boolean,
      default: false,
    },
    /* 上传文件大小限制(MB) */
    fileSize: {
      type: Number,
      default: 5,
    },
    /* 类型（base64格式、url格式） */
    type: {
      type: String,
      default: "url",
    }
  },
  data() {
    return {
      currentValue: "",
      uploadUrl: process.env.VUE_APP_BASE_API + "/minio/upload", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      MyAiEditor: null,
    }
  },
  computed: {
    styles() {
      let style = {}
      if (this.minHeight) {
        style.minHeight = `${this.minHeight}px`
      }
      if (this.height) {
        style.height = `${this.height}px`
      }
      return style
    }
  },
  watch: {
    value: {
      handler(val) {
        const newVal = val === null ? "" : val
        if (newVal !== this.currentValue) {
          this.currentValue = newVal
          if (this.MyAiEditor) {
            this.MyAiEditor.setContent(newVal)
          }
        }
      },
      immediate: true,
    },
  },
  mounted() {
    this.MyAiEditor = new AiEditor({
      element: this.$refs.divRef,
      contentIsMarkdown: false,
      contentRetention: false,
      contentRetentionKey: 'ai-editor-content',
      draggable: true,
      pasteAsText: false,
      placeholder: "点击输入内容...",
      content: this.value || '',
      onCreated: (editor) => {
        // 编辑器创建完成后，如果有初始值则设置
        if (this.value) {
          editor.setContent(this.value)
        }
      },
      onChange: (aiEditor) => {
        // 监听到用编辑器内容发生变化了，控制台打印编辑器的 html 内容...
        const html = aiEditor.getHtml()
        this.currentValue = html
        this.$emit("input", html)
        this.$emit("on-change", { html })
      },
      image: {
        uploadUrl: this.uploadUrl,
        defaultSize: 350,
        uploadFormName: "file", //上传时的文件表单名称
        uploadHeaders: {
          ...this.headers
        },
        uploaderEvent: {
          onSuccess: (file, response) => {
            //监听图片上传成功
            //注意：
            // 1、如果此方法返回 false，则图片不会被插入到编辑器
            // 2、可以在这里返回一个新的 json 给编辑器
            if (response.code === 200) {
              console.log('response.code===200', response.url)
              return {
                "errorCode": 0,
                "data": {
                  "src": response.url,
                  "alt": response.fileName
                }
              }
            }
          },
        },
        bubbleMenuItems: ["AlignLeft", "AlignCenter", "AlignRight", "delete"]
      },
      video: {
        uploadUrl: this.uploadUrl,
        uploadFormName: "file", //上传时的文件表单名称
        uploadHeaders: {
          ...this.headers
        },
        uploaderEvent: {
          onSuccess: (file, response) => {
            //监听图片上传成功
            //注意：
            // 1、如果此方法返回 false，则图片不会被插入到编辑器
            // 2、可以在这里返回一个新的 json 给编辑器
            if (response.code === 200) {
              console.log('response.code===200', response.url)
              return {
                "errorCode": 0,
                "data": {
                  "src": response.url,
                  "poster": "https://www.heixie.com/upload/heixei/20250728/b32d362fb62c4dceb17d9595a67203ee.jpg"
                }
              }
            }
          },
        },
      },
      attachment: {
        uploadUrl: this.uploadUrl,
        uploadFormName: "file", //上传时的文件表单名称
        uploadHeaders: {
          ...this.headers
        },
        uploaderEvent: {

          onSuccess: (file, response) => {
            //监听附件上传成功
            //注意：
            // 1、如果此方法返回 false，则附件不会被插入到编辑器
            // 2、可以在这里返回一个新的 json 给编辑器
            if (response.code === 200) {
              console.log('response.code===200', response.url)
              return {
                "errorCode": 0,
                "data": {
                  "href": response.url,
                  "fileName": response.fileName
                }
              }
            }
          },
          onFailed: (file, response) => {
            //监听附件上传失败，或者返回的 json 信息不正确
            console.log('attachment upload onFailed...')
          },
          onError: (file, error) => {
            //监听附件上传错误，比如网络超时等
            console.log('attachment upload onError...')
          },
        }
      },
    })
  },
  beforeDestroy() {
    if (this.MyAiEditor) {
      this.MyAiEditor.destroy()
      this.MyAiEditor = null
    }
    this.currentValue = ''
  },
  methods: {
    init() {

    },

  }
}
</script>

<style></style>
